<template>
  <div>
    <!-- <button @click="getOrderInfo()">点击获取订单信息</button> -->
    <!-- 新增用户弹窗 -->
    <el-dialog title="新增用户" :visible.sync="dialogVisible" width="60%">
      <!-- 新增用户的对话框 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 账号密码 -->
        <el-form-item label="用户名" prop="account">
          <el-input
            type="text"
            v-model="ruleForm.account"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="ruleForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model="ruleForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="ruleForm.sex" label="男">男</el-radio>
          <el-radio v-model="ruleForm.sex" label="女">女</el-radio>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input
            type="text"
            v-model="ruleForm.email"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-checkbox-group
            v-model="ruleForm.checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox v-for="city in cities" :label="city" :key="city">{{
              city
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 爱好 -->
        <el-form-item label="爱好" prop="hobby">
          <el-tag
            :key="tag"
            v-for="tag in ruleForm.dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
            >+ 其 他</el-button
          >
        </el-form-item>

        <!-- 年龄 -->
        <!-- <el-form-item label="年龄" prop="age">
          <el-input v-model.number="ruleForm.age"></el-input>
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog title="编辑用户" :visible.sync="dialogVisibleTwo" width="60%">
      <el-form
        :model="userEditRuleForm"
        status-icon
        :rules="rules"
        ref="userEditRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 账号密码 -->
        <el-form-item label="用户名" prop="account">
          <el-input
            type="text"
            v-model="userEditRuleForm.account"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="text"
            v-model="userEditRuleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 性别 -->
        <el-form-item label="性别" prop="sex">
          <el-input
            type="text"
            v-model="userEditRuleForm.sex"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input
            type="text"
            v-model="userEditRuleForm.email"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-input
            type="text"
            v-model="userEditRuleForm.address"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 爱好 -->
        <el-form-item label="爱好" prop="hobby">
          <el-input
            type="text"
            v-model="userEditRuleForm.hobby"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitUserEditForm('userEditRuleForm')"
            >确认编辑</el-button
          >
          <el-button @click="resetForm('userEditRuleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <div class="manage-header">
      <el-button @click="dialogVisible = true" type="primary">
        + 新增
      </el-button>
      
    </div>

    <div>
      <el-table
        :data="
          userInfo.filter(
            (data) =>
              !search ||
              data.account.toLowerCase().includes(search.toLowerCase())
          )
        "
        style="width: 100%"
      >
        <el-table-column label="用户id" prop="_id"> </el-table-column>
        <el-table-column label="用户名" prop="account"> </el-table-column>
        <el-table-column label="密码" prop="password"> </el-table-column>
        <el-table-column label="性别" prop="sex"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="地址" prop="address"> </el-table-column>
        <el-table-column label="爱好" prop="hobby"> </el-table-column>
        <el-table-column align="right">
          <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入关键字搜索"/>
        </template>
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import axios from "axios";
const cityOptions = ["上海", "北京", "广州", "深圳", "广西", "其他"];
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (value < 18) {
            callback(new Error("必须年满18岁"));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      userInfo:[],
      search: "",
      // 多选框
      checkAll: false,
      // checkedCities: ['上海', '北京','广西'],
      cities: cityOptions,
      isIndeterminate: true,

      // 标签
      // dynamicTags: ['篮球', '健身', '滑板'],
      inputVisible: false,
      inputValue: "",

      // 注册成功后关闭注册对话框
      dialogVisible: false,
      dialogVisibleTwo:false,

      // 获取数据
      ruleForm: {
        account: "",
        pass: "",
        sex: "",
        email: "",
        checkedCities: ["广西"],
        dynamicTags: ["篮球", "健身", "滑板"],
      },
      // 将已有的数据赋给弹出的对话框
      userEditRuleForm: {
        _id:"",
        account: "",
        password: "",
        sex: "",
        email: "",
        address: "",
        hobby: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        age: [{ validator: checkAge, trigger: "blur" }],
      },
    };
  },
  methods: {
    handleEdit(value) {
      this.dialogVisibleTwo = true
      this.userEditRuleForm._id = value._id
      this.userEditRuleForm.account = value.account
      this.userEditRuleForm.password = value.password
      this.userEditRuleForm.sex = value.sex
      this.userEditRuleForm.email = value.email
      this.userEditRuleForm.address = String(value.address)
      this.userEditRuleForm.hobby = String(value.hobby)
    },
    handleDelete(value) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.userEditRuleForm._id = value._id
          this.deleteUserInfo()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 删除用户信息
    deleteUserInfo(){
      axios.post("http://127.0.0.1:3000/deleteUserInfo", {
              _id: this.userEditRuleForm._id,
            })
            .then(
              () => {
                this.deleteUser_success();
                this.sendUserEditInfo()
              },
              () => {
                this.register_failing();
              }
            );
    },
    getOrderInfo() {
      axios.post("http://127.0.0.1:3000/orderInfo").then((res) => {
        console.log(res.data);
      });
    },
    // closeRegister(){
    //     this.$bus.$emit('closeRegister',this.dialogVisible)
    //   },
    //  注册成功后关闭注册对话框
    closeRegister() {
      this.$bus.$emit("closeRegister", this.dialogVisible);
    },
    // 提交注册信息
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios
            .post("http://127.0.0.1:3000/register", {
              account: this.ruleForm.account,
              password: this.ruleForm.pass,
              sex: this.ruleForm.sex,
              email: this.ruleForm.email,
              address: this.ruleForm.checkedCities,
              hobby: this.ruleForm.dynamicTags,
            })
            .then(
              () => {
                this.newUser_success();
                this.dialogVisible = false;
              },
              () => {
                this.register_failing();
              }
            );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 提交编辑信息
    submitUserEditForm() {
          axios
            .post("http://127.0.0.1:3000/userEditManage", {
              _id: this.userEditRuleForm._id,
              account: this.userEditRuleForm.account,
              password: this.userEditRuleForm.password,
              sex: this.userEditRuleForm.sex,
              email: this.userEditRuleForm.email,
              address: this.userEditRuleForm.address,
              hobby: this.userEditRuleForm.hobby,
            })
            .then(
              () => {
                this.EditUserInfo_success();
                this.dialogVisibleTwo = false;
                this.sendUserEditInfo()

              },
              () => {
                this.register_failing();
              }
            );
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClose(tag) {
      this.ruleForm.dynamicTags.splice(
        this.ruleForm.dynamicTags.indexOf(tag),
        1
      );
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.ruleForm.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    // 注册成功判断
    newUser_success() {
      this.$message({
        showClose: true,
        message: "新增用户数据成功！",
        type: "success",
      });
    },
    // 用户信息编辑成功判断
    EditUserInfo_success() {
      this.$message({
        showClose: true,
        message: "用户数据更新数据成功！",
        type: "success",
      });
    },
    // 用户信息删除成功判断
    deleteUser_success() {
      this.$message({
        showClose: true,
        message: "用户数据删除成功！",
        type: "success",
      });
    },
    // 注册失败判读
    register_failing() {
      this.$message({
        showClose: true,
        message: "注册账号失败！",
        type: "error",
      });
    },
    sendUserEditInfo(){
      axios.post("http://127.0.0.1:3000/login").then((res) => {
      this.userInfo = res.data;
      console.log(this.userInfo);
    });
    }
  },
  created() {
    this.sendUserEditInfo()
  },
};
</script>

<style>
</style>